use std::collections::BTreeMap;
use hmac::{Hmac, Mac};
use jwt::SignWithKey;
use sha2::Sha256;

use crate::config::{get, TokenType};

/// JWT结构参数
///
/// - `secret` - 场景
/// - `sub` - 内容
pub struct JWT {
    secret: String,
    sub: String,
}

impl JWT {
    pub fn new(secret: String, sub: String) -> Self {
        Self {
            secret, sub
        }
    }

    fn generate_jwt(&self) -> anyhow::Result<String> {
        let key: Hmac<Sha256> = Hmac::new_from_slice(self.secret.as_bytes())?;
        let mut claims = BTreeMap::new();
        claims.insert("sub", self.sub.clone());
        Ok(claims.sign_with_key(&key)?)
    }

    pub fn generate(&self) -> anyhow::Result<String> {
        let token_config = get().token()?;
        match token_config.ty() {
            TokenType::JWT => self.generate_jwt(),
        }
    }
}

#[test]
pub fn test_jwt_generate() {
    let jwt_a = JWT::new(String::from("secret"), String::from("sub"));
    let token = jwt_a.generate().unwrap();
    println!("{}", token);
}